#include "stream/pull_stream.h"
#include "stream/rtc_packet.h"

#include "ice/port_allocator.h"
#include <rtc_base/logging.h>
namespace xrtc
{

    PullStream::PullStream(EventLoop *el, PortAllocator *allocator, uint64_t uid, const std::string &stream_name,
                           bool audio, bool video, uint32_t log_id) : RtcStream(el, allocator, uid, stream_name, audio, video, log_id)

    {
        pc->SignalNackReceived.connect(this, &PullStream::OnNackReceived);
    }
    PullStream::~PullStream()
    {

        RTC_LOG(LS_INFO) << ToString() << " : Pull stream destory.";
    }

    std::string PullStream::CreateOffer()
    {
        RTCOfferAnswerOptions options;
        options.send_audio = audio;
        options.send_video = video;
        options.recv_audio = false;
        options.recv_video = false;
        return pc->CreateOffer(options);
    }
    void PullStream::AddAudioSource(std::vector<StreamParams> &source)
    {
        if (pc)
        {
            pc->AddAudioSource(source);
        }
    }

    void PullStream::AddVideoSource(std::vector<StreamParams> &source)
    {
        if (pc)
        {
            pc->AddVideoSource(source);
        }
    }
    int PullStream::SendPacket(webrtc::MediaType media_type,
                               std::shared_ptr<RtcPacket> packet,
                               bool is_retransmit)
    {

        if (!pc && state() != PeerConnectionState::kConnected)
        {
            return -1;
        }
        webrtc::RtpPacketToSend send_packet(nullptr);
        if (!send_packet.Parse(packet->buf, packet->len))
        {
            return -1;
        }
        if (is_retransmit)
        {
            send_packet.set_packet_type(webrtc::RtpPacketMediaType::kRetransmission);
        }
        return pc->SendPacket(media_type, send_packet);
    }
    void PullStream::SetSrInfo(webrtc::MediaType media_type, uint32_t rtp_timestamp,
                               webrtc::NtpTime ntp)
    {
        if (pc)
        {
            pc->SetSrInfo(media_type, rtp_timestamp, ntp);
        }
    }
    void PullStream::OnNackReceived(PeerConnection *, webrtc::MediaType media_type, const std::vector<uint16_t> &nack_list)
    {

        if (listener_)
        {
            listener_->OnNackReceived(this, media_type, nack_list);
        }
    }

} // namespace xrtc